#pragma once

#include "Common.h"

class ThreadCache
{
public:
    // 申请内存和释放对象
    void *Allocate(size_t size);
    void Deallocate(void *ptr, size_t size);

    // 从中心缓存获取对象
    void *FetchFromCentralCache(size_t index, size_t size);

private:
    FreeList _freelists[NFREELIST];
};


// TLS thread local storage
static __thread ThreadCache* pTLSThreadCache; // Linux环境下
// static _declspec(thread) ThreadCache* pTLSThreadCache = nullptr; // Windows环境下



void* ThreadCache::FetchFromCentralCache(size_t index, size_t size)
{
    // .....
    return nullptr;
}


void* ThreadCache::Allocate(size_t size)
{
    assert(size <= MAX_BYTES);
    size_t alignaSize = SizeClass::RoundUp(size); // 对齐后的size大小
    size_t index = SizeClass::Index(size); // 对应的桶的下标

    if (!_freelists[index].Empty())
    {
        return _freelists[index].Pop();
    }
    else
    {
        return FetchFromCentralCache(index, alignaSize);
    }

}




void ThreadCache::Deallocate(void *ptr, size_t size)
{
    assert(ptr);
    assert(size <= MAX_BYTES);

    // 找对应映射的自由链表桶，对象插入进去
    size_t index = SizeClass::Index(size);
    _freelists[index].Push(ptr);
}
